package com.nfit.rabbitmq.consumer;

import com.rabbitmq.client.*;

/**
 * ClassName:TopicConsumerB
 * Package:com.nfit.rabbitmq.consumer
 * Description
 *
 * @Author L
 * @Create 2024/11/21 16:10
 */
public class TopicConsumerB {
    /**
     * 自定义交换机名称
     */
    private static final String EXCHANGE_NAME = "test.topic";
    /**
     * 自定义队列
     */
    private static final String QUEUE_NAME = "b.queue";


    public static void main(String[] args) throws Exception {
        //初始化链接工厂并设置rabbitmq的主机地址
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672); //通信接口,1572是rabbitmq端口
        factory.setUsername("guest");
        factory.setPassword("guest");
        //创建链接
        Connection connection = factory.newConnection();
        //使用链接构建一个通信通道
        Channel channel = connection.createChannel();

        //指定交换机名称
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC,false);

        //声明队列
        channel.queueDeclare(QUEUE_NAME,true,false,false,null);

        //在消费者这一端进行路由绑定（binding）,也就是将路由key和交换机与queue绑定在一起
        //第三个参数就是路由的key,由于交换机的类型是topic,所以路由的key可以使用通配符,
        // 当消费者发送消息时,只要路由的key是以"a."开头,交换机就会把消息投递到这个queue中
        channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,"b.*");
        //消息回调接口
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println("message"+message);
        };
        //接收
        channel.basicConsume(QUEUE_NAME,true,deliverCallback,consumerTag -> {});
    }

}
